package listener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;

import com.example.pyphone3.R;

public class AndroidFileListenerActivity extends Activity {
    private FileObserver mFileObserver;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(null == mFileObserver) {
            mFileObserver = new SDCardFileObserver(Environment.getExternalStorageDirectory().getPath());
            mFileObserver.startWatching(); //开始监听
        }
    }

    public void onDestory() {
        if(null != mFileObserver) mFileObserver.stopWatching(); //停止监听
    }

    static class SDCardFileObserver extends FileObserver {
        //mask:指定要监听的事件类型，默认为FileObserver.ALL_EVENTS
        public SDCardFileObserver(String path, int mask) {
            super(path, mask);
        }

        public SDCardFileObserver(String path) {
            super(path);
        }

        @Override
        public void onEvent(int event, String path) {
            final int action = event & FileObserver.ALL_EVENTS;
            switch (action) {
                case FileObserver.ACCESS:
                    System.out.println("event: 文件或目录被访问, path: " + path);
                    break;

                case FileObserver.DELETE:
                    System.out.println("event: 文件或目录被删除, path: " + path);
                    break;

                case FileObserver.OPEN:
                    System.out.println("event: 文件或目录被打开, path: " + path);
                    break;

                case FileObserver.MODIFY:
                    System.out.println("event: 文件或目录被修改, path: " + path);
                    break;
            }
        }

    }
}